package com.zone.service.controller;

import java.util.List;
import java.io.IOException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zone.common.log.annotation.Log;
import com.zone.common.log.enums.BusinessType;
import com.zone.common.security.annotation.RequiresPermissions;
import com.zone.service.domain.BoxInoutRecord;
import com.zone.service.service.IBoxInoutRecordService;
import com.zone.common.core.web.controller.BaseController;
import com.zone.common.core.web.domain.AjaxResult;
import com.zone.common.core.utils.poi.ExcelUtil;
import com.zone.common.core.web.page.TableDataInfo;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.zone.common.security.utils.SecurityUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import java.net.URLEncoder;

/**
 * 款箱出入库记录Controller
 * 
 * @author liuyang
 * @date 2025-10-31
 */
@RestController
@RequestMapping("/boxInoutRecord")
public class BoxInoutRecordController extends BaseController
{
    @Autowired
    private IBoxInoutRecordService boxInoutRecordService;

    /**
     * 查询款箱出入库记录列表
     */
    @RequiresPermissions("service:boxInoutRecord:list")
    @GetMapping("/list")
    public TableDataInfo list(BoxInoutRecord boxInoutRecord)
    {
        startPage();
        List<BoxInoutRecord> list = boxInoutRecordService.selectBoxInoutRecordList(boxInoutRecord);
        return getDataTable(list);
    }

    /**
     * 导出款箱出入库记录列表
     */
    @RequiresPermissions("service:boxInoutRecord:export")
    @Log(title = "款箱出入库记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BoxInoutRecord boxInoutRecord)
    {
        List<BoxInoutRecord> list = boxInoutRecordService.selectBoxInoutRecordList(boxInoutRecord);
        ExcelUtil<BoxInoutRecord> util = new ExcelUtil<BoxInoutRecord>(BoxInoutRecord.class);
        util.exportExcel(response, list, "款箱出入库记录数据");
    }

    /**
     * 获取款箱出入库记录详细信息
     */
    @RequiresPermissions("service:boxInoutRecord:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(boxInoutRecordService.selectBoxInoutRecordById(id));
    }

    /**
     * 新增款箱出入库记录
     */
    @RequiresPermissions("service:boxInoutRecord:add")
    @Log(title = "款箱出入库记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BoxInoutRecord boxInoutRecord)
    {
        return toAjax(boxInoutRecordService.insertBoxInoutRecord(boxInoutRecord));
    }

    /**
     * 修改款箱出入库记录
     */
    @RequiresPermissions("service:boxInoutRecord:edit")
    @Log(title = "款箱出入库记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BoxInoutRecord boxInoutRecord)
    {
        return toAjax(boxInoutRecordService.updateBoxInoutRecord(boxInoutRecord));
    }

    /**
     * 删除款箱出入库记录
     */
    @RequiresPermissions("service:boxInoutRecord:remove")
    @Log(title = "款箱出入库记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(boxInoutRecordService.deleteBoxInoutRecordByIds(ids));
    }
    
    /**
     * 导出款箱出入库记录模板
     */
    @RequiresPermissions("service:boxInoutRecord:export")
    @Log(title = "款箱出入库记录", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        String templatePath = "templates/boxinoutrecord.xls";
        
        ClassPathResource resource = new ClassPathResource(templatePath);
        if (!resource.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        try {
            // 设置正确的 Content-Type 和编码
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            
            // 安全编码文件名
            String fileName = URLEncoder.encode("款箱出入库记录导入模板.xls", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            
            // 流式拷贝
            StreamUtils.copy(resource.getInputStream(), response.getOutputStream());
            response.flushBuffer();
            
        } catch (IOException e) {
            try {
                response.reset();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件下载失败");
            } catch (IOException ignored) {}
        }
    }
    
    /**
     * 导入款箱出入库记录数据
     */
    @RequiresPermissions("service:boxInoutRecord:add")
    @Log(title = "款箱出入库记录", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult execlImport(@RequestParam("file") MultipartFile file, boolean updateSupport) {
        try {
            if (file == null || file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }
            
            // 创建ExcelUtil实例
            ExcelUtil<BoxInoutRecord> util = new ExcelUtil<BoxInoutRecord>(BoxInoutRecord.class);
            
            // 解析Excel文件
            List<BoxInoutRecord> boxInoutRecordList = util.importExcel(file.getInputStream());
            
            if (boxInoutRecordList == null) {
                return AjaxResult.error("导入数据解析失败，请检查Excel文件格式");
            }
            
            if (boxInoutRecordList.isEmpty()) {
                return AjaxResult.error("导入数据为空，请检查Excel文件是否包含数据");
            }
            
            // 设置创建人
            for (BoxInoutRecord boxInoutRecord : boxInoutRecordList) {
                boxInoutRecord.setCreateBy(SecurityUtils.getUsername());
            }
            
            return toAjax(boxInoutRecordService.batchInsertBoxInoutRecord(boxInoutRecordList));
        } catch (Exception e) {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
}